package controller;

import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import entity.Violation_record;
import service.Violation_recordService;
import service.impl.Violation_recordServiceimpl;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/violation_recordController")
public class Violation_recordController extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String op=req.getParameter("op");
        HttpSession session=req.getSession(true);
        PrintWriter out=resp.getWriter();
        Violation_recordService dao=new Violation_recordServiceimpl();
        if ("Violation".equals(op)) {
            String searchKey = req.getParameter("searchKey");

            String pageStr = req.getParameter("page");
            String pageSizeStr = req.getParameter("pageSize");

            int currentPage = 0; // 默认第一页
            int pageSize = 5; // 默认每页10条

            try {
                currentPage = Integer.parseInt(pageStr);
                currentPage = Math.max(currentPage, 0); // 确保页码不小于0
            } catch (NumberFormatException e) {
                currentPage = 0;
            }

            try {
                pageSize = Integer.parseInt(pageSizeStr);
                pageSize = Math.max(pageSize, 1); // 确保每页至少1条
            } catch (NumberFormatException e) {
                pageSize = 10;
            }

            Violation_recordService vio = new Violation_recordServiceimpl();
            List<Violation_record> list = Collections.emptyList();
            int totalCount = 0;
            boolean hasNextPage = false;

            try {
                if(StringUtils.isNullOrEmpty(searchKey)){
                    // 获取当前页数据
                    list = vio.Violation_record(null, currentPage, pageSize);
                }else{
                    list = vio.Violation_record(Integer.valueOf(searchKey), currentPage, pageSize);
                }

                // 获取总记录数
                totalCount = vio.getTotalCount(String.valueOf(searchKey));
                // 计算总页数
                int totalPages = (int) Math.ceil((double)totalCount / pageSize);
                // 检查是否有下一页
                hasNextPage = currentPage < totalPages - 1;

                // 如果是AJAX请求，返回JSON格式数据
                if("XMLHttpRequest".equals(req.getHeader("X-Requested-With"))) {
                    Map<String, Object> result = new HashMap<>();
                    result.put("data", list);
                    result.put("currentPage", currentPage);
                    result.put("totalPages", totalPages);
                    result.put("totalCount", totalCount);
                    resp.setContentType("application/json");
                    out.print(JSON.toJSONString(result));

                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if ("INSERT".equals(op)){
            String student_name=req.getParameter("student_name");
            String violation_type=req.getParameter("violation_type");
            String punishment=req.getParameter("punishment");
            String record_time=req.getParameter("record_time");
            String auditor=req.getParameter("auditor");
            String status=req.getParameter("status");

            // 创建统一的响应对象
            Map<String, Object> response = new HashMap<>();
            try {
                // 验证必填字段
                if(StringUtils.isNullOrEmpty(student_name) ||
                        StringUtils.isNullOrEmpty(violation_type) ||
                        StringUtils.isNullOrEmpty(punishment)) {
                    response.put("success", false);
                    response.put("message", "姓名、违纪类型和处分措施不能为空");
                    out.print(JSON.toJSONString(response));
                    return;
                }

                int studentId = dao.select(student_name);
                if(studentId > 0){
                    int insert = dao.INSERT(studentId, student_name, violation_type,
                            punishment, record_time, auditor, status);
                    response.put("success", insert > 0);

                    response.put("message",insert>0?"成功":"失败");
                } else {
                    response.put("success", false);
                    response.put("message", "该学生不存在，无法添加记录");
                }
                System.out.println(response);
                out.print(JSON.toJSONString(response));

            } catch (SQLException | ClassNotFoundException e) {
                response.put("success", false);
                response.put("message", "数据库操作异常：" + e.getMessage());
                out.print(JSON.toJSONString(response));
                e.printStackTrace();
            }
        }
        if ("update".equals(op)){
            String id = req.getParameter("id");
            String violation_type=req.getParameter("violation_type");
            String punishment=req.getParameter("punishment");
            String record_time=req.getParameter("record_time");
            String auditor=req.getParameter("auditor");
            String status=req.getParameter("status");
            Map<String,Object> map=new HashMap<>();
            try {
                int result = dao.UPDATE(id, violation_type, punishment, record_time, auditor, status);
                Map<String,Object> response=new HashMap<>();
                response.put("success", result > 0);
                response.put("message", result > 0 ? "修改成功" : "修改失败");
                out.print(JSON.toJSONString(response));
            } catch (SQLException | ClassNotFoundException e) {
                map.put("success", false);
                map.put("message", "数据库操作失败");
                out.print(JSON.toJSONString(map));
                e.printStackTrace();
            }
        }
        if ("delete".equals(op)) {
            String id = req.getParameter("id");
            Map<String, Object> response = new HashMap<>();
            resp.setContentType("application/json");

            try {
                if(StringUtils.isNullOrEmpty(id)) {
                    response.put("success", false);
                    response.put("message", "ID不能为空");
                    out.print(JSON.toJSONString(response));
                    return;
                }

                int result = dao.delete(Integer.parseInt(id));
                response.put("success", result > 0);
                response.put("message", result > 0 ? "删除成功" : "删除失败，记录可能不存在");
                out.print(JSON.toJSONString(response));
            } catch (NumberFormatException e) {
                response.put("success", false);
                response.put("message", "ID格式不正确");
                out.print(JSON.toJSONString(response));
                e.printStackTrace();
            } catch (SQLException | NamingException | ClassNotFoundException e) {
                response.put("success", false);
                response.put("message", "数据库操作异常: " + e.getMessage());
                out.print(JSON.toJSONString(response));
                e.printStackTrace();
            }
        }

    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}






